<?php

namespace app\modules\admincategory\controllers;

use Yii;
use common\models\Category;
use common\models\search\CategorySearch;
use common\models\CateAttr;
use common\models\CateAttrVal;
//use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\components\AdminController;
use common\models\Tools;

/**
 * CategoryController implements the CRUD actions for Category model.
 */
class CategoryController extends AdminController
{
	public $enableCsrfValidation=false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                ],
            ],
        ];
    }
    
    public function init()
    {
        parent::init();
    }


    /**
     * Lists all Category models.
     * @return mixed
     */
    public function actionIndex()
    {
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录";
            \common\models\Tools::outputjson($output);
        }
        $data = Category::getAllCate();
        return $this->render('index', [
            'data' => $data,
        ]);
    }

    /**
     * Displays a single Category model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Category model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $parent = Tools::GetSafeParam('parent', 0, 0);
        $name = Tools::GetSafeParam('name', '', 1);
        $grade = Tools::GetSafeParam('grade', 0, 0);
        
        if($name === ""){
            $output['success'] = 0;
            $output['msg'] = "请输入分类名称";
            Tools::outputjson($output);
        }
        if($grade === 0){
            $output['success'] = 0;
            $output['msg'] = "分类等级错误";
            Tools::outputjson($output);
        }
        
        $model = new Category();
        $model->parent = $parent;
        $model->name = $name;
        $model->grade = $grade+1;
        $model->addtime = time();
        if($model->save()){
            $output['success'] = 1;
            $output['msg'] = "更新成功！";
            Tools::outputjson($output);
        }else{
            $output['success'] = 0;
            $output['msg'] = "更新失败！".$model->errors;
            Tools::outputjson($output);
        }
    }

    /**
     * Updates an existing Category model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate()
    {
        $id = Tools::GetSafeParam('id', 0, 0);
        $name = Tools::GetSafeParam('name', '', 1);
        
        $model = $this->findModel($id);
        
        if($name === ""){
            $output['success'] = 1;
            $output['data'] = $model->toArray();
            Tools::outputjson($output);
        }else{
            $model->name = $name;
            $model->save();
            $output['success'] = 1;
            $output['msg'] = "更新成功！";
            Tools::outputjson($output);
        }
    }

    /**
     * Deletes an existing Category model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete()
    {
        $id = Tools::GetSafeParam('id', 0, 0);
        if($this->findModel($id)->delete()){
            $output['success'] = 1;
            $output['msg'] = "删除成功！";
            Tools::outputjson($output);
        }
        else{
            $output['success'] = 0;
            $output['msg'] = "删除失败！";
            Tools::outputjson($output);
        }

//        return $this->redirect(['index']);
    }

    /**
     * Finds the Category model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Category the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Category::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
    
    /**
     * 分类对应的商品属性列表
     */
    public function actionAttrlist(){
        $cate_id = Tools::GetSafeParam('cate_id', 0, 0);
        $cate_name = Tools::GetSafeParam('cate_name', "", 1);
        $data = \common\models\CateAttr::getAttrlistByCate($cate_id);
        
        foreach($data as $key=>$value){
            $data[$key]['optional'] = CateAttrVal::getValInStringByAttrId($value['id']);
        }
        
        $type_arr = [0=>"输入框",1=>"单选项",2=>"多选项"];
        $is_must_arr = [0=>"选填",1=>"必填"];
        
        return $this->render('attrlist', [
            'data' => $data,
            'cate_id' => $cate_id,
            'cate_name' => $cate_name,
            'type_arr' => $type_arr,
            'is_must_arr' => $is_must_arr
        ]);
    }
    
    public function actionAttrcreate(){
        $cate_id = Tools::GetSafeParam('cate_id', 0, 0);
        $name = Tools::GetSafeParam('name', "", 1);
        $optional = Tools::GetSafeParam('optional', "", 1);
        $type = Tools::GetSafeParam('type', 0, 0);
        $sort = Tools::GetSafeParam('sort', 0, 0);
        $is_must = Tools::GetSafeParam('is_must', 0, 0);
        
        
        if($cate_id == 0){
            $output['success'] = 1;
            $output['msg'] = "分类信息错误";
            Tools::outputjson($output);
        }
        if($name == ""){
            $output['success'] = 1;
            $output['msg'] = "属性名称不能为空";
            Tools::outputjson($output);
        }
        if(($type == 1 || $type == 2) && $optional == ""){
            $output['success'] = 1;
            $output['msg'] = "备选值不能为空";
            Tools::outputjson($output);
        }
        
        $cate_attr_model = new CateAttr();
        
        $cate_attr_model->cate_id = $cate_id;
        $cate_attr_model->name = $name;
        $cate_attr_model->type = $type;
        $cate_attr_model->sort = $sort;
        $cate_attr_model->is_must = $is_must;
        
        $cate_attr_model->addtime = time();
        if($cate_attr_model->save()){
            if($optional != "" && ($type==1 || $type==2)){
                $optional_arr = explode("\n", $optional);
                foreach($optional_arr as $option_val){
                    $option_val = trim($option_val);
                    $attr_id = $cate_attr_model->id;
                    $attr_val_model = new CateAttrVal();
                    $attr_val_model->attr_id = $attr_id;
                    $attr_val_model->val = $option_val;
                    $attr_val_model->addtime = time();
                    $attr_val_model->save();
                }
            }
        }
        $output['success'] = 1;
        $output['msg'] = "添加成功";
        Tools::outputjson($output);
    }
    
    public function actionAttrupdate(){
        $attr_id = Tools::GetSafeParam('attr_id', 0, 0);
        
        $model = CateAttr::findOne([$attr_id]);
        
        $name = Tools::GetSafeParam('name', "", 1);
        $optional = Tools::GetSafeParam('optional', "", 1);
        $type = Tools::GetSafeParam('type', 0, 0);
        $sort = Tools::GetSafeParam('sort', 0, 0);
        $is_must = Tools::GetSafeParam('is_must', 0, 0);
        
        if($name == "" && $type== 0){
            $output['success'] = 1;
            $output['data'] = $model->toArray();
            $output['optional'] = CateAttrVal::getValInTextareaByAttrId($attr_id);
            Tools::outputjson($output);
        }else{
            $model->name = $name;
            $model->type = $type;
            $model->sort = $sort;
            $model->is_must = $is_must;
            $model->save();
            
            CateAttrVal::deleteAll(['attr_id'=>$attr_id]);
            
            if($optional != "" && ($type==1 || $type==2)){
                $optional_arr = explode("\n", $optional);
                foreach($optional_arr as $option_val){
                    $option_val = trim($option_val);
                    $attr_val_model = new CateAttrVal();
                    $attr_val_model->attr_id = $attr_id;
                    $attr_val_model->val = $option_val;
                    $attr_val_model->addtime = time();
                    $attr_val_model->save();
                }
            }
        }
        $output['success'] = 1;
        $output['msg'] = "修改成功";
        Tools::outputjson($output);
    }
    
    
    public function actionAttrdelete(){
        $attr_id = Tools::GetSafeParam('attr_id', 0, 0);
        $model = CateAttr::findOne([$attr_id]);
        if($model->delete()){
            $output['success'] = 1;
            $output['msg'] = "删除成功";
            Tools::outputjson($output);
        }else{
            $output['success'] = 0;
            $output['msg'] = "删除失败";
            Tools::outputjson($output);
        }
    }
    
}
